package main

import (
	"New-lesson-part2/internal"
	"New-lesson-part2/internal/register"
	"New-lesson-part2/product_web/handler"
	"New-lesson-part2/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"go.uber.org/zap"
	"os"
	"os/signal"
	"syscall"
)

var Reg register.ConsulRegisTry
var randUUID string
var port int
var WebSrvHost string

func init() {
	port = util.GenRandomPort()
	randUUID = uuid.New().String()
	name := internal.AppConf.ProductWebConfig.SrvName
	id := randUUID
	WebSrvPort := port
	WebSrvHost := internal.AppConf.ProductWebConfig.Host
	tags := internal.AppConf.ProductWebConfig.Tags
	err := Reg.WebRegister(WebSrvHost, name, id, WebSrvPort, tags)

	if err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println("注册成功")
	}
}

func main() {

	r := gin.Default()
	//consul服务健康检查
	r.GET("health", handler.HealthHandler)

	//productGroup := r.Group("/productGroup")
	//{
	//	productGroup.GET("/list", handler.ProductListHandler)
	//	productGroup.POST("/add", handler.AddHandler)
	//	productGroup.GET("/detail/:id", handler.DetailHandler)
	//	productGroup.POST("/delete/:id", handler.DeleteHandler)
	//	productGroup.POST("/update", handler.UpdateHandler)
	//
	//}
	addr := fmt.Sprintf("%s:%d", internal.AppConf.ProductWebConfig.Host, port)

	go func() {
		err := r.Run(addr)
		if err != nil {
			zap.S().Panic(addr + "启动失败" + err.Error())
		} else {
			zap.S().Info(addr + "启动成功")
		}
	}()
	q := make(chan os.Signal)
	signal.Notify(q, syscall.SIGINT, syscall.SIGTERM)
	<-q
	err := Reg.DeRegister(randUUID)
	if err != nil {
		zap.S().Error("注销失败" + randUUID + ":" + WebSrvHost + err.Error())
	} else {
		zap.S().Error("注销成功" + randUUID + ":" + WebSrvHost)
	}
}
